<?php
namespace app\home\controller;
use app\admin\model\Activity;
use app\admin\model\Sign;
use think\Controller;
use think\Cookie;
use think\Cache;

class Index extends Controller {
	
	private $_conf = array();
	
	public function __construct() {
		parent::__construct();
		$config_data = db('config')->select();
		foreach( $config_data as $k => $v ) {
			$this->_conf[$v['name']] = $v['data'];
		}
		
		$this->assign("config" , $this->_conf);
		$this->_conf['rule_data'] = $this->_conf['rule_data'] ? unserialize( $this->_conf['rule_data'] ) : array();
		foreach( $this->_conf['rule_data'] as $k => $v ) {
			$rule_data[$v['num']] = $v['day'];
		}
		$this->_conf['rule_data'] = $rule_data;
	}
	
    //活动列表
    public function index(){
        $list = db('activity')->where("status = 1 and endtime > '" . date("Y-m-d",time())."'")->paginate();

        $this->assign('list',$list);

        return $this->fetch();
    }
    //我的活动
    public function listmy(){
        $tel = input('tel');
        if (!$tel){
            $tel = Cookie::get('tel');
        }
		if( !$tel ) {
			header("Location:" . url("index/checkMobile"));
		}
        $mylist = db('user_sign')->where(array('tel'=>$tel))->select();
        if ($mylist){
            foreach ($mylist as $key=>$val){
                $acinfo = db('activity')->where(array('activity_id'=>$val['activity_id']))->find();
                $mylist[$key]['acinfo'] = $acinfo;
                if ($val['status'] == 0){
                    if (strtotime($acinfo['endtime']) < time()){
                        $mylist[$key]['status'] = -1;
                        db('user_sign')->update(array('status'=>-1,'sign_id'=>$val['sign_id']));
                    }
                }
            }
        }

        $this->assign('list',$mylist);
        return $this->fetch('list-my');
    }
	
	public function checkMobile() {
		return $this->fetch();
	}
	public function checkedMobiles() {
		$data = input();
        if (!$data['tel'])return json_encode(array('msg'=>'请填写你的电话','code'=>-1));
        if (!$data['code'])return json_encode(array('msg'=>'请输入验证码','code'=>-1));
		//判断验证码
		$system_code = Cache::get( "mobile_sms_".$data['tel'] );
		if($system_code != $data['code'] ) {
			return json_encode(array('msg'=>'验证码错误','code'=>-1));
		}
		Cache::rm( "mobile_sms_".$data['tel'] );
		Cookie::set('tel', $data['tel']);
		return json_encode(array('msg'=>'认证成功','code'=>1));
	}
    //详情
    public function event(){
        $id = input('id');

        if ($id){
            $activityinfo = db('activity')->find($id);
        }
        $Activity = new Activity();
        $Activity->addclick($id);
        $this->assign('info',$activityinfo);
        return $this->fetch();
    }
	
	public function qrcode(){
		$id = input('id');
		if (!$id) return "";
		vendor("phpqrcode.phpqrcode");
		$data = $this->_conf['site_url'] . url("index/checkData" , array("id" => $id));
		$level = 'L';
		$size = 6;
		\QRcode::png($data, false, $level, $size);
	}
	
	public function checkData() {
		$id = input('id');
        if (!$id){
            exit("数据错误");
        }
		$activityinfo = db('user_sign')->field("sign_id,wx_name,status,wx_name_small,activity_id")->find($id);
		if( !$activityinfo ) {
			exit("数据不存在");
		}
		$infos = db('activity')->find($activityinfo['activity_id']);
		if( !$infos ) {
			exit("数据不存在");
		}
		$activityinfo = array_merge(  $infos , $activityinfo );
        $this->assign('info',$activityinfo);
		$check_tel = Cookie::get('check_tel');
		$this->assign("check" , $check_tel);
		return $this->fetch();
	}
	
	public function sysetmCheckData(){
		$data = input();
		if (!$data['id'])return json_encode(array('msg'=>'数据错误','code'=>-1));
		
		$activityinfo = db('user_sign')->find($data['id']);
		
		if( !$activityinfo ) {
			return json_encode(array('msg'=>'报名数据不存在','code'=>-1));
		}
		
		$check_tel = Cookie::get('check_tel');
		
		if( !$check_tel ) {
		
			if (!$data['tel'])return json_encode(array('msg'=>'请填写你的电话','code'=>-1));
			if (!$data['code'])return json_encode(array('msg'=>'请输入验证码','code'=>-1));
			//判断验证码
			$system_code = Cache::get( "mobile_auth_sms_".$data['tel'] );
			if($system_code != $data['code'] ) {
				return json_encode(array('msg'=>'验证码错误','code'=>-1));
			}
		
		} else {
			
			$data['tel'] = $check_tel;
			
		}
		
		Cache::rm( "mobile_auth_sms_".$data['tel'] );
		
		if( !$user_info = db("user")->where(array("mobile" => $data['tel'] , 'status'=>1 ))->find() ){
			
			Cookie::delete('check_tel');
			
			return json_encode(array('msg'=>'核销人员不存在','code'=>-1));
		}
		
		db('user_sign')->update(array("sign_id" => $data['id'] , 'status' => 1, 'user_id' => $user_info['user_id'] , 'enter_time' => date("Y-m-d H:i:s")));
		
		Cookie::set('check_tel', $data['tel']);
		
		$member_info = db("member")->where(array("mobile" => $activityinfo['tel']))->find();
		
		if( $member_info ) {
		
			db("member")->where(array("mobile" => $activityinfo['tel']))->update(array("last_time" => time() , "num" => $member_info['num'] + 1));
		
		}
		
		return json_encode(array('msg'=>'核销成功','code'=>1));
	}
	
	public function sendCheckSms(){
		$mobile = input("post.mobile");
		if(empty($mobile)){
			exit(json_encode(array("status" => 0 , "msg" => "手机号不能为空")));
		}
		if( !db("user")->where(array("mobile" => $mobile,"status" => 1))->find()) {
			exit(json_encode(array("status" => 0 , "msg" => "您不是核销人员，核销失败！")));
		}
		$rand = rand(100000,999999);
		Cache::set("mobile_auth_sms_".$mobile , $rand, 300);
		
		\app\home\extend\sms::sendSms($mobile , $rand , "SMS_116580707");
		
		exit(json_encode(array("status" => 1 , "smscode" => '')));
	}
	
    //二维码
    public function code(){
        return $this->fetch();
    }
    //报名
    public function signup(){
        $data = input();
        if (!$data['username'])exit( json_encode(array('msg'=>'请填写你的名字','code'=>-1)) );
        if (!$data['tel'])exit( json_encode(array('msg'=>'请填写你的电话','code'=>-1)) );
        if (!$data['code'])exit( json_encode(array('msg'=>'请输入验证码','code'=>-1)) );

        $activity_info = db('activity')->find($data['id']);

        if (!$activity_info)exit( json_encode(array('msg'=>'活动不存在','code'=>-1)) );

        if (strtotime($activity_info['endtime'])<time()){
            exit( json_encode(array('msg'=>'活动已过期','code'=>-1)));
        }
		
		if( db("user_sign")->where(array("tel" => $data['tel'] , 'activity_id' => $data['id']))->find() ) {
				exit( json_encode(array('msg'=>'您已报名，请勿重复报名','code'=>-1)) );
		}

        $insertdata['activity_id'] = $data['id'];
        $insertdata['wx_name'] = $data['username'];
		$insertdata['wx_name_small'] = $data['childname'];
        $insertdata['tel'] = $data['tel'];
        $insertdata['sign_time'] = date('Y-m-d H:i:s',time());
        $insertdata['createtime'] = date('Y-m-d H:i:s',time());
        $insertdata['enter_time'] = '1970-01-01 00:00:00';   //0000-00-00 00:00:00
        $insertdata['status'] = 0;
		
		
        //$nonum = db('user_sign')->where(array('tel'=>$data['tel'],'status'=>-1))->count();
        //$infos = db("member")->where(array("mobile" => $data['tel']))->find();
		//if ($infos && $infos['invalid']>=3){
        //    return json_encode(array('msg'=>'爽约超过三次，无法报名','code'=>-1));
        //}
		$limit_data = db("limit_time")->where("`mobile` = '".$insertdata['tel']."' AND `limit_time` > " . time())->find();
		if( $limit_data ) {
			exit( json_encode(array('msg'=>'您有'.$limit_data['num'].'次爽约，'.date("Y-m-d" , $limit_data['limit_time']).'之后才能正常参加活动。','code'=>-1)) );
		}
		
		if( !$infos ) {
			db("member")->insert(array(
				'name' => $data['username'],
				'mobile' => $data['tel']
			));
		}
		
		//判断验证码
		$system_code = Cache::get( "mobile_sms_".$data['tel'] );
		if($system_code != $data['code'] ) {
			exit( json_encode(array('msg'=>'验证码错误','code'=>-1)) );
		}
		Cache::rm( "mobile_sms_".$data['tel'] );
        if (db('user_sign')->insert($insertdata)){

            if ($activity_info['signnum']>=1){
                $activity_info['signnum'] -=1;
            }else{
                exit( json_encode(array('msg'=>'名额已满','code'=>-1)) );
            }
            db('activity')->update($activity_info);
            Cookie::set('tel', $data['tel']);
            exit( json_encode(array('msg'=>'报名成功','code'=>1)) );

        }else{
            exit( json_encode(array('msg'=>'报名失败','code'=>-1)) );
        }
    }
    //取消报名
    public function del(){
        $id = input('id');
        if ($id){
            $signinfo = db('user_sign')->find($id);
            if ($signinfo){
                $activityinfo = db('activity')->find($signinfo['activity_id']);
                if ($activityinfo){
                    $status = db('user_sign')->delete($id);
                    if ($status>0){
                        $activityinfo['signnum'] +=1;
                        db('activity')->update($activityinfo);
                        $this->success('取消成功',url('index/listmy'));
                    }else{
                        $this->error('取消失败',url('index/listmy'));
                    }
                }
            }
        }
        $this->error('未知错误',url('index/listmy'));
    }

    //首页
    public function index1(){
        //MEDIA信息
        $media=$this->getMedia();
        $this->assign('media', $media);
        $this->assign('crumb', array());
        //给模版给以一个当前时间戳的值
        $this->assign('demo_time',$this->request->time());
        return $this->siteFetch(get_site('tpl_index'));
    }
    //注册
    public function reg(){
        if (input('post.')){
            $status=model('User')->add();
            if ($status>0){
                return ajaxReturn(200,'注册成功',url('login'));
            }else{
                return ajaxReturn(0,'注册失败');
            }
        }else{
            return $this->siteFetch('reg');
        }
    }
    //登录
    public function login(){
        if (input('post.')){
            $email = input('post.email');
            $passWord = input('post.password');
            if(empty($email)||empty($passWord)){
                return ajaxReturn(0,'用户名或密码未填写！');
            }
            //查询用户
            $model = model('User');
            $map = array();
            $map['email'] = $email;
            $userInfo = $model->getWhereInfo($map);
            if(empty($userInfo)){
                return ajaxReturn(0,'登录用户不存在！');
            }
            if($userInfo['status']!=1){
                return ajaxReturn(0,'该用户已被禁止登录！');
            }
            if($userInfo['password']<>md5($passWord)){
                return ajaxReturn(0,'您输入的密码不正确！');
            }
            if($model->setLogin($userInfo)){
                return ajaxReturn(200,'登录成功',url('user/userHome'));
            }else{
                return ajaxReturn(0,'登录失败！');
            }
        }else{
            return $this->siteFetch('login');
        }
    }
    //退出登录
    public function loginOut(){
        model('User')->logout();
        return redirect('index/index');
    }
	
	public function sendSms() {
		$mobile = input("post.mobile");
		if(empty($mobile)){
			exit(json_encode(array("status" => 0 , "msg" => "手机号不能为空")));
		}
		$rand = rand(100000,999999);
		Cache::set("mobile_sms_".$mobile , $rand , 300);
		
		\app\home\extend\sms::sendSms($mobile , $rand , "SMS_116580707");
		
		exit(json_encode(array("status" => 1 , "smscode" => '')));
	}
	
	/**
	 * 爽约报名脚本
	 */
	public function shells() {
		$data = db("activity")->where("endtime < '".date("Y-m-d")."' AND status != 3")->select();
		foreach( $data as $k => $v ) 
		{
			//爽约
			$user_info = db("user_sign")->where("status = 0 and activity_id = " .$v['activity_id'])->select();
			foreach( $user_info as $m => $n ) {
				$data = db("member")->where("mobile = '".$n['tel']."'")->find();
				$invalid = $data['invalid'] + 1;
				if( isset( $this->_conf['rule_data'][$invalid] ) && $this->_conf['rule_data'][$invalid] ) {
					$limit_day = $this->_conf['rule_data'][$invalid];
					$limit_time = strtotime(date("Y-m-d" , strtotime("+".$limit_day." day")));
					//增加限制规则
					db("limit_time")->insert(array(
						"mobile" => $n['tel'],
						"num" => $invalid,
						"limit_time" => $limit_time
					));
				}
				
				//修改爽约数量
				db("member")->where(array("mobile" => $n['tel']))->update(array("invalid" => $invalid));
				
				//修改数据为爽约
				db("user_sign")->where(array("sign_id" => $n['sign_id']))->update(array("status" => -1));
			}
			
			//正常参与
			$user_info = db("user_sign")->where("status = 1 and activity_id = " .$v['activity_id'])->select();
			foreach( $user_info as $m => $n ) {
				$data = db("member")->where("mobile = '".$n['tel']."'")->find();
				$num = $data['num'] + 1;
				db("member")->where(array("mobile" => $n['tel']))->update(array("num" => $num,'last_time' => time()));
			}
			
			//修改活动状态
			db("activity")->where("endtime < '".date("Y-m-d")."' AND status != 2")->update(array("status" => 3));
		}
	}
}
